<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cookie;//使用cookie
class LoginController extends Controller
{
    //登陆
    public function login(Request $request)
    {
        if($request->isMethod('post')){
            //dd($request->Cookie('adminpwd'));
            $data=$_POST;
            if ($data['name']=='' || $data['password']=='') {
                return back()->withErrors('登录名和密码不能为空');
            }elseif (!\DB::table('admin')->where(array('name'=>$data['name']))->first()) {
                return back()->withErrors('登录账户不存在');
            }else{
                $password=\DB::table('admin')->where(array('name'=>$data['name']))->value('password');
                if (!Hash::check($data['password'],$password)) {
                    return back()->withErrors('登录密码填写错误');
                }else{
                    $userid=\DB::table('admin')->where(array('name'=>$data['name']))->value('id');
                    //点击记住密码
                    if (!empty($data['online'])) {
                        Cookie::queue("adminname", $data['name'], 60 * 24 * 30);//记录一个月(单位:分钟)
                        Cookie::queue("adminpwd", $data['password'], 60 * 24 * 30);
                    } else {
                        //没有点击，删除cookie
                        Cookie::queue('adminname',null,-1);
                        Cookie::queue("adminpwd",null,-1);
                    }
                    session(['user_id'=>$userid]);
                    return redirect('admin/index');
                }
            }
        }else{
            //如果cookie不存在，则不用自动登录
            if (!empty($request->Cookie('adminname'))) {
                //赋值session
                session(['adminname' => $request->Cookie('adminname')]);
                session(['adminpwd' => $request->Cookie('adminpwd')]);
                //分配数据
                $adminname=session('adminname');
                $adminpwd=session('adminpwd');
                $online=1;
            }else{
                $adminname='';
                $adminpwd='';
                $online=0;
            }
            return view('admin/login',compact('adminname','adminpwd','online'));
        }
    }
    //退出登陆
    public function loginOut()
    {
        session()->flush();
        return redirect('admin/login');
    }

}
